package com.leetcode;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @author lefly
 * @version 1.0
 * @classname No46
 * @description
 * @date 2021/2/5 下午3:27
 */
public class No46 {
    public static void main(String[] args) {
        int[] data = {1,2,3};
        List<List<Integer>> res = permute(data);
        print(res);
    }

    private static void print(List<List<Integer>> res) {
        int len = res.size();
        for (int i = 0; i < len; i++) {
            List<Integer> sub = res.get(i);
            int subLen = sub.size();
            for (int j = 0; j < subLen; j++) {
                System.out.print(sub.get(j));
                System.out.print(" ");
            }
            System.out.println();
        }
    }

    public static List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        if(nums == null || nums.length == 0){
            return res;
        }
        boolean[] used = new boolean[nums.length];
        List<Integer> list = new ArrayList<>();
        subPermute(res,list,used,nums);
        return res;
    }

    private static void subPermute(List<List<Integer>> res, List<Integer> list, boolean[] used, int[] nums) {
        if(list.size() == nums.length){
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if(used[i]){
                continue;
            }
            used[i] = true;
            list.add(nums[i]);
            subPermute(res,list,used,nums);
            list.remove(list.size() - 1);
            used[i] = false;
        }
    }

}
